package com.csvw.skr.console.service;

import com.csvw.skr.basic.entity.User;
import com.google.common.collect.Lists;

import com.webonn.frame.core.Pagination;
import com.webonn.frame.db.MyDao;
import com.webonn.frame.util.MyStringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.ws.rs.core.MultivaluedMap;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * Created by Administrator on 2016/9/18.
 */
@Service
public class UserService {
    @Autowired
    private MyDao dao;

    public Pagination queryUsers(int start, int limit, MultivaluedMap<String, String> filter) {
        Pagination p = new Pagination();
        p.setStart(start);
        p.setLimit(limit);
        List<Object> paramsList = Lists.newArrayList();

        String sql = "select t_user.pk_empno as empno, t_user.name, t_user.phone, t_user.role, t_user.organization, t_user.active, organization.name as organizationName, t_user.email, t_user.job, job.name as jobTitle, " +
                "t_user.position, position.name as positionName " +
                "from csvw_skr_basic_user t_user " +
                "left join csvw_skr_basic_job job on job.pk_code=t_user.job " +
                "left join csvw_skr_basic_position position on position.pk_code=t_user.position " +
                "left join csvw_skr_basic_organization organization on organization.pk_code=t_user.organization " +
                "where 1=1  ";
        String search = filter.getFirst("search");
        if (!MyStringUtil.isNullOrEmpty(search)) {
            sql += " and CONCAT_WS(',', t_user.pk_empno, t_user.email, t_user.name, t_user.phone,t_user.organization) like ? ";
            paramsList.add("%" + search.trim() + "%");
        }
        sql += " order by t_user.created desc ";
        return dao.queryResultToMapPagination(sql, p, paramsList.toArray());
    }

    public Map<String, Object> getUserByUserName(String username) {
        String get_user_sql = "select t_user.pk_empno as empno, t_user.name, t_user.phone, t_user.role, t_user.organization, organization.name as organizationName, " +
                "t_user.email, t_user.job, job.name as jobTitle, t_user.position, position.name as positionName, organization.name as organizationShortName, " +
                "IFNULL((SELECT oldcode FROM csvw_skr_basic_organization WHERE t_user.organization LIKE CONCAT('%',pk_code,'%') AND headquarters = 2 AND LEVEL = 2), oldcode) AS rboOldcode " +
                "from csvw_skr_basic_user t_user " +
                "left join csvw_skr_basic_job job on job.pk_code=t_user.job " +
                "left join csvw_skr_basic_position position on position.pk_code=t_user.position " +
                "left join csvw_skr_basic_organization organization on organization.pk_code=t_user.organization " +
                "where t_user.active=true and (t_user.pk_empno=? or t_user.email=? or t_user.phone = ?)  ";
        List<Map<String, Object>> result = Lists.newArrayList();
        get_user_sql += " order by t_user.created desc ";
        result.addAll(dao.queryResultToMap(get_user_sql, new Object[]{username, username, username}));
        if (result.size() > 0) {
            return result.get(0);
        } else {
            return null;
        }
    }


    public User addUser(User entity) {
        Date addTime = new Date();
        entity.setCreated(addTime);
        entity.setUpdated(addTime);
        return dao.persist(entity);
    }

    public User getUser(String empno) {
        return dao.get(empno, User.class);
    }

    public User updateUser(User user) {
        User user_old = getUser(user.getEmpno());
        user.setCreated(user_old.getCreated());
        user.setActive(user_old.isActive());
        user.setPassword(user_old.getPassword());
        user.setRole(user_old.getRole());
        user.setUpdated(new Date());
        return dao.persist(user);
    }

    public boolean deleteUser(String empno) {
        User user_old = getUser(empno);
        if (Objects.nonNull(user_old)) {
            user_old.setActive(false);
            user_old.setPhone("delete_" + user_old.getPhone());
            return Objects.nonNull(dao.persist(user_old));
        } else {
            return false;
        }
    }

    public User addUserRole(String userId, List<String> roleIds) {
        String roles = "";
        for (int i = 0; i < roleIds.size(); i++) {
            roles += roleIds.get(i);
            if (i != roleIds.size() - 1) roles += ",";
        }

        User user = getUser(userId);
        user.setRole(roles);
        return dao.persist(user);
    }

    public List<Map<String, Object>> queryUserRole(String userId) {
        if (userId.equals(0)) return Lists.newArrayList();

        User user = getUser(userId);
        if (user == null) return Lists.newArrayList();

        String sql = "select role.pk_code as code ,role.name,role.description from csvw_skr_basic_role role" +
                " where role.active=true order by role.created asc";
        List<Map<String, Object>> roles = dao.queryResultToMap(sql, null);

        if (!MyStringUtil.isNullOrEmpty(user.getRole())) {
            List<String> userRoleIds = Lists.newArrayList(user.getRole().split(","));
            for (Map<String, Object> role : roles) {
                if (userRoleIds.contains(role.get("code"))) {
                    role.put("checked", true);
                } else {
                    role.put("checked", false);
                }
            }
        }
        return roles;
    }

    public User getExist(String type, String value) {
        String sql = "select * from csvw_skr_basic_user u " +
                "where " + type + "= ?";
        return dao.uniqueResult(sql, User.class, new Object[]{value});
    }
}
